package models

import (
	"errors"
	"fmt"
	"reflect"
	"strings"
	"time"

	"gitee.com/lzqysoft/ga_wz_backend/libs"
	"gitee.com/lzqysoft/ga_wz_backend/libs/encrypt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type SfCase struct {
	Id            string    `orm:"column(id);pk"`
	Phone         string    `orm:"column(phone)"`
	Remark        string    `orm:"column(remark);null"`
	Status        int       `orm:"column(status)"`
	Isdelete      int       `orm:"column(isdelete)"`
	Ctime         time.Time `orm:"column(ctime);type(timestamp with time zone)"`
	Creater       string    `orm:"column(creater);null"`
	Cid           string    `orm:"column(cid);null"`
	Utime         time.Time `orm:"column(utime);type(timestamp with time zone)"`
	Updater       string    `orm:"column(updater);null"`
	Uid           string    `orm:"column(uid);null"`
	Title         string    `orm:"column(title);null"`
	No            string    `orm:"column(no);null"`
	JyType        int       `orm:"column(jy_type);null"`
	Category      int       `orm:"column(category);null"`
	StartTime     time.Time `orm:"column(start_time);type(timestamp with time zone);null"`
	Start         int       `orm:"column(start);null"`
	CoutTime      time.Time `orm:"column(cout_time);type(timestamp with time zone);null"`
	Cout          int       `orm:"column(cout);null"`
	CoutUser      string    `orm:"column(cout_user);null"`
	CoutPhone     string    `orm:"column(cout_phone);null"`
	FinishTime    time.Time `orm:"column(finish_time);type(timestamp with time zone);null"`
	Finish        int       `orm:"column(finish);null"`
	AppointTime   time.Time `orm:"column(appoint_time);null"`
	AppointUser   string    `orm:"column(appoint_user);null"`
	AppointUserId string    `orm:"column(appoint_user_id);null"`
	DeptId        string    `orm:"column(dept_id);null"`
	DeptName      string    `orm:"column(dept_name);null"`
	IsAdditional  int       `orm:"column(is_additional);null"`
	AdditionalId  string    `orm:"column(additional_id);null"`
	Lock          int       `orm:"column(lock);null"`
	First         int       `orm:"column(first);null"`
}

func (t *SfCase) TableName() string {
	return "sf_case"
}

func init() {
	orm.RegisterModel(new(SfCase))
}

func GenSfCase() *SfCase {
	var m SfCase
	m.Id = encrypt.GetGuid()
	m.Status = 1
	m.Isdelete = 0
	m.Ctime = time.Now()
	m.Utime = time.Now()
	m.Id = encrypt.GetGuid()
	return &m
}

// AddSfCase insert a new SfCase into database and returns
// last inserted Id on success.
func AddSfCase(m *SfCase) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetSfCaseById retrieves SfCase by Id. Returns error if
// Id doesn't exist 
func GetSfCaseById(id string) (v *SfCase, err error) {
	o := orm.NewOrm()
	v = &SfCase{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetSfCaseByUserIdAndType(userId string, jdlx int) ([]SfCase, error) {
	o := orm.NewOrm()
	var sf []SfCase
	_, err := o.QueryTable(new(SfCase)).Filter("cid", userId).Filter("isdelete", 0).Filter("status", 1).
		Filter("jy_type", jdlx).OrderBy("-ctime", "-updater").
		All(&sf)
	return sf, err
}

// GetAllSfCase retrieves all SfCase matches certain condition. Returns empty list if
// no records exist
func GetAllSfCase(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(SfCase))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []SfCase
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdateSfCase updates SfCase by Id and returns error if
// the record to be updated doesn't exist
func UpdateSfCaseById(m *SfCase) (err error) {
	o := orm.NewOrm()
	v := SfCase{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteSfCase deletes SfCase by Id and returns error if
// the record to be deleted doesn't exist
func DeleteSfCase(id string) (err error) {
	o := orm.NewOrm()
	v := SfCase{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&SfCase{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

func GetSfCaseByUserIdAndStatus(userId string) ([]SfCase, error) {
	o := orm.NewOrm()
	var sf []SfCase
	_, err := o.QueryTable(new(SfCase)).Filter("cid", userId).Filter("status", 1).Filter("isdelete", 0).All(&sf)
	return sf, err
}

func SoftDeleteSfCase(user *User, ids []string) error {
	o := orm.NewOrm()
	//num, err := o.QueryTable("user").Update(orm.Params{
	//	"nums": orm.ColValue(orm.ColAdd, 100),
	//})
	_, err := o.QueryTable(new(SfCase)).Filter("id__in", ids).Update(orm.Params{
		"isdelete": 1,
		"updater":  user.Abbr,
		"utime":    time.Now(),
	})
	return err
}

func GetLegalCase(offset int) (int64, []SfCase, error) {
	o := orm.NewOrm()
	var l []SfCase
	qs := o.QueryTable(new(SfCase)).Filter("Status__gt", 1).
		Filter("IsAdditional", 0).Filter("Isdelete", 0).OrderBy("-Ctime")
	total, err := qs.Count()
	if err != nil {
		return 0, nil, err
	}
	_, err = qs.Limit(10).Offset(offset * 10).All(&l)
	if err != nil {
		return 0, nil, err
	}
	//beego.Debug(l)
	return total, l, nil
}

func GetALlCase() ([]orm.Params, error) {
	o := orm.NewOrm()

	var l []orm.Params
	_, err := o.QueryTable(new(SfCase)).Filter("Status__gt", 1).
		Filter("IsAdditional", 0).Filter("Isdelete", 0).OrderBy("-Ctime").Values(&l, "Title", "No",
		"JyType", "Status", "Creater", "DeptName", "Phone", "Ctime")
	//beego.Debug(l)
	//m := make(map[string]interface{})
	for k, _ := range l {
		l[k]["JyType"] = libs.GetJyType(l[k]["JyType"].(int64))
		//t,_:= time.Parse("2006-01-02 15:04:05",l[k]["Ctime"].(string))
		//t.Format("2006-01-02")
		l[k]["Ctime"] = l[k]["Ctime"].(time.Time).Format("2006-01-02")
		l[k]["Status"] = libs.GetJyStatus(l[k]["Status"].(int64))
		beego.Debug(l[k]["Ctime"])
	}
	return l, err
}

func DelSfCaseRelated(sfCase SfCase) error {
	o := orm.NewOrm()
	o.Begin()
	// 删除流程信息
	//var f Flowinstance
	if _, err := o.QueryTable(new(Flowinstance)).Filter("Busyname", sfCase.TableName()).Filter("Busyid", sfCase.Id).
		Update(orm.Params{
			"Isdelete": 1,
		}); err != nil {
		beego.Debug(err)
		o.Rollback()
		return err
	}

	// 删除todo
	//var f SfTodoManager
	if _, err := o.QueryTable(new(SfTodoManager)).Filter("BusyName", sfCase.TableName()).Filter("BusyId", sfCase.Id).
		Update(orm.Params{
			"Isdelete": 1,
		}); err != nil {
		beego.Debug(err)
		o.Rollback()
		return err
	}
	//var f SfTodoUser
	if _, err := o.QueryTable(new(SfTodoUser)).Filter("BusyName", sfCase.TableName()).Filter("BusyId", sfCase.Id).
		Update(orm.Params{
			"Isdelete": 1,
		}); err != nil {
		beego.Debug(err)
		o.Rollback()
		return err
	}
	// 删除 sf_rate
	//var f SfRate
	if _, err := o.QueryTable(new(SfRate)).Filter("BusyName", sfCase.TableName()).Filter("BusyId", sfCase.Id).
		Update(orm.Params{
			"Isdelete": 1,
		}); err != nil {
		beego.Debug(err)
		o.Rollback()
		return err
	}
	// 删除caseitem
	//var f SfCaseItem
	if _, err := o.QueryTable(new(SfCaseItem)).Filter("SfCaseId", sfCase.Id).
		Update(orm.Params{
			"Isdelete": 1,
		}); err != nil {
		beego.Debug(err)
		o.Rollback()
		return err
	}
	// 删除 sfcase
	if _, err := o.QueryTable(new(SfCase)).Filter("Id", sfCase.Id).Delete();  err != nil {
		beego.Debug(err)
		o.Rollback()
		return err
	}
	return o.Commit()
}
